<template>
  <div class="app-container">
    <query
      ref="query"
      @submit="pageLoad"
      @add="addHandle"
    />
    <grid
      ref="grid"
      :remote-method="loadData"
      total-count-name="recordsCount"
    >
      <el-table-column align="center" label="ID" width="95">
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column align="center" prop="userName" label="UserName" />
      <el-table-column align="center" prop="phone" label="Phone" />
      <el-table-column align="center" prop="email" label="Email" />
      <el-table-column label="Update" prop="update" align="center" />
      <el-table-column label="LastTime" align="center">
        <template slot-scope="scope">
          {{ scope.row.lastTime }}
        </template>
      </el-table-column>
      <el-table-column label="Create" prop="create" align="center" />
      <el-table-column label="Creation Time" prop="creationTime" align="center" />
      <el-table-column align="center" label="operate">
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="showEditDialog(scope.row.id)"
          >edit</el-button>
          <el-popconfirm
            title="Confirm deletion?"
            confirm-button-text="OK"
            cancel-button-text="Cancel"
            @onConfirm="() => deleteUser(scope.row.id)"
          >
            <el-button
              slot="reference"
              style="margin-left: 10px;"
              type="text"
            >delete</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </grid>
    <edit-dialog
      ref="editDialogRef"
      @close="pageLoad"
    />
  </div>
</template>

<script>
import { getUserList, deleteUser } from '@/api/user'
import Grid from '@/components/Grid'
import { EditDialog, Query } from './components'

export default {
  components: {
    Grid,
    Query,
    EditDialog
  },
  mounted() {
    this.pageLoad()
  },
  methods: {

    pageLoad() {
      this.$refs.grid.loadData()
    },

    loadData() {
      const { params } = this.$refs.query || {}
      return getUserList(params).then(data => {
        return {
          data: data.items,
          recordsCount: data.total
        }
      })
    },

    addHandle() {
      this.$refs.editDialogRef.show()
    },

    async deleteUser(id) {
      await deleteUser({ id })
      this.$message({
        type: 'success',
        message: 'delete success'
      })
    },

    /**
     * show edit or add dialog
     * @params id
     */
    showEditDialog(id) {
      this.$refs.editDialogRef.show(id)
    }
  }
}
</script>

<style scoped>
  .app-container {
    height: 100%;
  }
</style>
